package com.fenxiangtech.mall.web.controller.v1;

import com.fenxiangtech.mall.entity.Address;
import com.fenxiangtech.mall.exception.ParameterMismatchException;
import com.fenxiangtech.mall.exception.SuccessMessage;
import com.fenxiangtech.mall.exception.UnknownErrorException;
import com.fenxiangtech.mall.service.AddressService;
import com.fenxiangtech.mall.service.UserTokenService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.validation.BindingResult;
import org.springframework.validation.ObjectError;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletResponse;
import java.util.List;

/**
 * @author zhangjiashun
 */
@Controller("addressControllerV1")
@RequestMapping("/v1/address")
public class AddressController {

    @Autowired
    AddressService addressService;

    @Autowired
    UserTokenService userTokenService;

    @GetMapping
    @ResponseBody
    public Address getUserAddress() {
        Long uid = userTokenService.getCurrentUID();
        return addressService.getAddressByUserID(uid);
    }

    @PostMapping
    @ResponseBody
    public SuccessMessage saveOrUpdateAddress(@Validated @RequestBody Address address,
                                              BindingResult bindingResult,
                                              HttpServletResponse response) {
        if (bindingResult.hasErrors()) {
            List<ObjectError> errors = bindingResult.getAllErrors();
            throw new ParameterMismatchException(errors.get(0).getDefaultMessage());
        }
        Long currentUID = userTokenService.getCurrentUID();
        address.setUserId(currentUID);
        boolean success = addressService.saveOrUpdateAddress(address);
        if (!success) {
            throw new UnknownErrorException();
        }
        SuccessMessage successMessage = new SuccessMessage();
        response.setStatus(successMessage.getStatusCode());
        return successMessage;
    }

}
